package com.lifp.thread.juc;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Description 信号灯 Semaphore
 * @Author lfp
 * @Date 2022/8/5
 * @Version 1.0
 */
public class SemaphoreDemo {
    //场景：抢车位，6辆汽车停3个停车位


    public static void main(String[] args) {
        //1、创建Semaphore，设置许可数量
        Semaphore semaphore = new Semaphore(3);

        //2、模拟6辆汽车
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                try {
                    //3、抢占车位
                    semaphore.acquire();

                    System.out.println(Thread.currentThread().getName() + " 抢到了车位");

                    //4、设置随机停车时间
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));

                    //5、模拟离开
                    System.out.println(Thread.currentThread().getName() + " ---离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //6、释放
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }

}
